<template>
    <view class="app-container">
        <!--         顶部导航栏 -->
        <!--        <PageHeader-->
        <!--                v-if="curPageStyleInfo.showHeader !== false"-->
        <!--                :title="curPageStyleInfo.navigationBarTitleText"-->
        <!--                :showBack="curPageStyleInfo.showLeftArrow"-->
        <!--                :showBackText="curPageStyleInfo.showLeftArrow"-->
        <!--                :title-color="curPageStyleInfo.navigationBarTextStyle"-->
        <!--                :nav-bg-color="curPageStyleInfo.navigationBarBackgroundColor"-->
        <!--                @back="handleBack"-->
        <!--        />-->
        <view class="page-content" ref="pageContentRef" :style="{paddingBottom:pageContentStyle.paddingBottom}">
            <view class="u-f">
                <u-title class="wallet-style">
                    <template #prefix>
                        <view class="custom-prefix u-f u-f-ajc u-f-ac">
                            <img src="/static/img/wallet.png" alt="">
                        </view>
                    </template>
                    <text>3333333333333333333
                    </text>
                </u-title>
                <!-- 新增：年月切换区域 -->
                <view class="date-picker-container">
                    <!-- 左箭头（切换上一年/月） -->
                    <uni-icons
                            type="left"
                            size="20"
                            color="#8c8c8c"
                            class="arrow-icon"
                            @click="handleSwitchPrev()"
                    />

                    <!-- 当前年月显示 + 下拉触发 -->
                    <view class="current-date" @click="handleShowDatePicker">
                        <text class="date-text">{{ currentYear }}年{{ currentMonth }}月</text>
                    </view>

                    <!-- 右箭头（切换下一年/月） -->
                    <uni-icons
                            type="right"
                            size="20"
                            color="#8c8c8c"
                            class="arrow-icon"
                            @click="switchNext()"
                    />
                </view>
            </view>

            <!-- 收支概览区域 -->
            <view class="overview-container">
                <view class="balance-card">
                    <u-title class="card-title">本月月结</u-title>
                    <text class="total-balance">¥{{ totalBalance.toFixed(2) }}</text>
                    <view class="income-expense">
                        <view class="item">
                            <text class="label">本月收入</text>
                            <text class="amount income-color">+¥{{ totalIncome.toFixed(2) }}</text>
                        </view>
                        <view class="divider"></view>
                        <view class="item">
                            <text class="label">本月支出</text>
                            <text class="amount expense-color">-¥{{ totalExpense.toFixed(2) }}</text>
                        </view>
                        <view class="divider"></view>
                        <view class="item">
                            <text class="label">本月欠款</text>
                            <text class="amount expense-color">-¥{{ totalExpense.toFixed(2) }}</text>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 当月明细标题 -->
            <view class="monthly-title">
                <u-title class="title-text">{{ curMonthTitle }} 收支明细</u-title>
            </view>

            <!-- 收支明细列表 -->
            <view class="records-container">
                <!-- 无数据提示 -->
                <view class="empty-tip" v-if="records.length === 0">
                    <text class="empty-icon">📊</text>
                    <text class="empty-text">暂无收支记录</text>
                    <text class="empty-desc">点击右上角按钮添加第一条记录</text>
                </view>

                <!-- 明细列表 -->
                <view class="record-list">
                    <view class="record-item" v-for="(record, index) in records" :key="index">
                        <view class="record-left">
                            <view class="record-icon" :style="{ backgroundColor: record.type === 'income' ? incomeIconBg : expenseIconBg }">
                                <text class="icon-text">{{ record.icon }}</text>
                            </view>
                            <view class="record-info">
                                <text class="record-name">{{ record.name }}</text>
                                <text class="record-time">{{ formatTime(record.time) }}</text>
                            </view>
                        </view>
                        <text class="record-amount" :class="record.type === 'income' ? 'income-color' : 'expense-color'">
                            {{ record.type === 'income' ? '+' : '-' }}¥{{ record.amount.toFixed(2) }}
                        </text>
                    </view>
                </view>
            </view>


            <!--            添加账单-->
            <view  @click="handleNavigateToAddRecord" class="add-record-btn u-f u-f-ac u-f-ajc">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
                    <!-- 完全匹配 Unicon outline 风格：2px 线条、圆角、透明填充 -->
                    <path
                            d="M12 5v14M5 12h14"
                            stroke="currentColor"
                            stroke-width="2"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            fill="none"
                    />
                </svg>
            </view>
        </view>
        <!-- 新增：年月选择器弹窗（默认隐藏） -->
        <uni-popup
                ref="chooseRef"
                v-model="showDatePicker"
                type="bottom"
                :mask-click="true"
                class="date-popup"
        >
            <view class="popup-header u-f u-f-ac u-f-ajs">
                <view class="popup-title">选择年月</view>
                <view>
                    <button size="mini" @click="handleChangeDate" type="primary"
                            style="color:#ffffff;backgroundColor:#1890ff;borderColor:#1AAD19"
                            hover-class="is-hover">确定</button>
                </view>
            </view>
            <!-- 原生日期选择器（限制只选年月） -->
            <picker-view
                    :value="pickerValue"
                    @change="handlePickerChange"
                    class="picker-view"
            >
                <picker-view-column class="picker-column">
                    <view class="picker-item" v-for="year in yearRange" :key="year">{{ year }}年</view>
                </picker-view-column>
                <picker-view-column class="picker-column">
                    <view class="picker-item" v-for="month in 12" :key="month">{{ month }}月</view>
                </picker-view-column>
            </picker-view>
        </uni-popup>

        <!-- 底部导航栏 -->
        <TabBar
                v-if="curPageStyleInfo.showTabBar !== false"
        />
    </view>
</template>

<script setup lang="ts">
    import {computed, onMounted, ref, watch} from 'vue'
    import {handleGetCurSys, handleGetPageInfo} from "@/utils/utils";
    import PageHeader from '@/components/pageHeader/index.vue';
    import handleToast from "@/plugins/model/toast";
    import TabBar from '@/components/tabBar/index.vue';
    import {onShow} from "@dcloudio/uni-app";
    const uToastRef = ref()
    const curVal = ref(0)
    const title = ref('Hello')
    let chooseRef = ref()
    const curPageStyleInfo = ref(handleGetPageInfo().getCurrentStyle())
    let pageContentStyle = ref({
        paddingTop:0,
        paddingBottom:0,
    })
    let pageContentRef = ref();
    // 当前月份
    const curMonthTitle = ref('');
    // 新增：年月切换核心变量
    let currentYear = ref<number>(new Date().getFullYear()); // 当前选中年份
    let currentMonth = ref<number>(new Date().getMonth() + 1); // 当前选中月份
    let showDatePicker = ref<boolean>(false); // 是否显示年月选择弹窗
    let yearRange = ref<number[]>([]); // 年份选择范围（近5年）
    let pickerValue = ref<number[]>([currentYear.value, currentMonth.value - 1]); // 日期选择器初始值
    // 右侧菜单配置
    const rightMenu = [
        {
            icon: '⚙️',
            onClick: () => {
                uni.navigateTo({ url: '/pages/setting/setting' });
            }
        }
    ];


    // 收支记录类型定义
    interface AccountRecord {
        id: number;
        name: string; // 收支名称
        type: 'income' | 'expense'; // 类型：收入/支出
        amount: number; // 金额
        time: string; // 时间（格式：YYYY-MM-DD HH:mm）
        icon: string; // 图标（Unicode）
        category: string; // 分类（如：餐饮、工资、交通等）
    }

    // 全局样式变量（可抽离到 less 变量文件）
    const incomeColor = '#52c41a'; // 收入色（绿色）
    const expenseColor = '#ff4d4f'; // 支出色（红色）
    const incomeIconBg = 'rgba(82, 196, 26, 0.1)'; // 收入图标背景
    const expenseIconBg = 'rgba(255, 77, 79, 0.1)'; // 支出图标背景

    // 收支记录列表
    const records = ref<AccountRecord[]>([
        {
            id: 1,
            name: '工资',
            type: 'income',
            amount: 8000,
            time: '2025-11-05 09:30',
            icon: '💼',
            category: '薪资'
        },
        {
            id: 2,
            name: '午餐',
            type: 'expense',
            amount: 35,
            time: '2025-11-05 12:15',
            icon: '🍜',
            category: '餐饮'
        },
        {
            id: 3,
            name: '交通费',
            type: 'expense',
            amount: 8,
            time: '2025-11-04 18:40',
            icon: '🚌',
            category: '交通'
        },
        {
            id: 4,
            name: '副业收入',
            type: 'income',
            amount: 1500,
            time: '2025-11-03 16:20',
            icon: '💰',
            category: '其他收入'
        },
        {
            id: 5,
            name: '超市购物',
            type: 'expense',
            amount: 126,
            time: '2025-11-02 10:10',
            icon: '🛒',
            category: '购物'
        }
    ]);

    // 计算总收支
    const totalIncome = computed(() => {
        return records.value
            .filter(record => record.type === 'income')
            .reduce((sum, item) => sum + item.amount, 0);
    });

    const totalExpense = computed(() => {
        return records.value
            .filter(record => record.type === 'expense')
            .reduce((sum, item) => sum + item.amount, 0);
    });

    const totalBalance = computed(() => {
        return totalIncome.value - totalExpense.value;
    });

    // 格式化日期（显示月-日 时:分）
    const formatTime = (timeStr: string) => {
        const date = new Date(timeStr);
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hour = date.getHours().toString().padStart(2, '0');
        const minute = date.getMinutes().toString().padStart(2, '0');
        return `${month}-${day} ${hour}:${minute}`;
    };

    // 设置当前月份标题
    const setCurrentMonthTitle = () => {
        const date = new Date();
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        curMonthTitle.value = `${year}年${month}月`;
    };

    // 跳转到添加记账记录页面
    const handleNavigateToAddRecord = () => {
        uni.navigateTo({ url: '/pageHome/addRecord/index' });
    };

    // 跳转到添加记账记录页面
    const handleNavigateToEditRecord = () => {
        uni.navigateTo({ url: '/pageHome/editRecord/index' });
    };

    // 页面加载初始化
    onShow(() => {
        setCurrentMonthTitle();
    });
    // 新增：初始化年份范围（近5年，包含当前年）
    const handleInitYearRange = () => {
        const current = new Date().getFullYear();
        const range = [];
        for (let i = current - 4; i <= current; i++) {
            range.push(i);
        }
        yearRange.value = range;
        // 设置选择器默认年份索引（当前年在range中的位置）
        pickerValue.value[0] = yearRange.value.findIndex(y => y === currentYear.value)+1;
        pickerValue.value[1] = pickerValue.value[1]<12?pickerValue.value[1]+1:pickerValue.value[1];
        // console.log(pickerValue.value[1],'dddddddd');
    };

    // 新增：切换上一年/月
    const handleSwitchPrev = () => {
        if (currentMonth.value > 1) {
            currentMonth.value--;
        } else {
            currentMonth.value = 12;
            currentYear.value--;
            // 限制年份不小于最小年份
            if (currentYear.value < yearRange.value[0]) {
                currentYear.value = yearRange.value[0];
                currentMonth.value = 1;
            }
        }
    };
    // 新增：切换下一年/月
    const switchNext = () => {
        const currentDate = new Date();
        const maxYear = currentDate.getFullYear();
        const maxMonth = currentDate.getMonth() + 1;

        // 不能超过当前年月
        if (currentYear.value < maxYear) {
            if (currentMonth.value < 12) {
                currentMonth.value++;
            } else {
                currentMonth.value = 1;
                currentYear.value++;
            }
        } else if (currentYear.value === maxYear && currentMonth.value < maxMonth) {
            currentMonth.value++;
        }
        ;
    }
    const handleShowDatePicker = ()=>{
        showDatePicker.value = true
        chooseRef.value.open('bottom')
    }
    // 新增：日期选择器变化事件
    const handlePickerChange = (e: UniApp.PickerViewChangeEvent) => {
        console.log(e.detail.value,"2222222222");
        const [yearIndex, monthIndex] = e.detail.value;
        if(yearIndex>=yearRange.value.length){
            pickerValue.value[0] = yearRange.value.findIndex(y => y === yearRange.value[yearIndex-1])+1
        }else{
            pickerValue.value[0] =  yearRange.value.findIndex(y => y === yearRange.value[yearIndex])
        }
        if(monthIndex>12){
            pickerValue.value[1] = 12;
        }else{
            pickerValue.value[1] = monthIndex;
        }
        console.log(pickerValue.value[0]);
        console.log(currentMonth.value);
        // 设置选择器默认年份索引（当前年在range中的位置）
        showDatePicker.value = false;
    };

    //修改日期
    const handleChangeDate = ()=>{
        // pickerValue.value = [
        //         // yearRange.value.findIndex(y => y === pickerValue[0]),
        //         // newMonth - 1
        //     ];
        // chooseRef.value.close()
        currentYear.value =  yearRange.value[pickerValue.value[0]==0?pickerValue.value[0]:pickerValue.value[0]-1]
        currentMonth.value =  pickerValue.value[1]
        // 通过时间发起请求

        chooseRef.value.close()
    }

    // 新增：监听当前年月变化，更新选择器值
    // watch([currentYear, currentMonth], ([newYear, newMonth]) => {
    //     pickerValue.value = [
    //         yearRange.value.findIndex(y => y === newYear),
    //         newMonth - 1
    //     ];
    // });
    // 处理返回按钮点击
    const handleBack = () => {
        if (getCurrentPages().length > 1) {
            // router.back();
        } else {
            // 如果是首页，不做任何操作或显示提示
            uni.showToast({
                title: '已经是首页',
                icon: 'none'
            });
        }
    };
    onShow(() => {
        // 设置CSS变量
        const updateCssVariables = () => {
            const curSys = handleGetCurSys();
            let addHeaderHeight = 0;
            if(curSys == 'mp-weixin'){
                addHeaderHeight = 24
            }else if(curSys == 'web' || curSys == 'app'){
                addHeaderHeight = 54
            }else{
                addHeaderHeight = 24
            }
            // 顶部导航栏高度
            // const headerHeight = uni.getSystemInfoSync().statusBarHeight + 24;
            const headerHeight = uni.getSystemInfoSync().statusBarHeight + addHeaderHeight;
            pageContentStyle.value.paddingBlock = `${headerHeight}px`

            // 底部导航栏高度
            const tabBarHeight = 50 + (uni.getSystemInfoSync().safeAreaInsets?.bottom || 0);
            pageContentStyle.value.paddingBottom = `${tabBarHeight}px`
        };

        updateCssVariables();
        /* #ifdef H5 */
        // 监听窗口大小变化，更新CSS变量
        window.addEventListener('resize', updateCssVariables);
        /* #endif */

        handleInitYearRange();
    });
</script>

<style lang="less" scoped>
    // 全局变量
    @page-bg: #f1f3f7;
    @card-bg: #fff;
    @text-primary: #333;
    @text-secondary: #8c8c8c;
    @border-color: #eee;
    @income-color: #52c41a;
    @expense-color: #ff4d4f;
    @spacing: 16px 5px;

    .page-content {
        min-height: 100vh;
        padding-bottom: 20px;
    }

    .wallet-style{
        margin-right: 10px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        width:80px;
        border-radius: 5px;
        padding:5px 7px;
        background:#FFFFFF;
        .custom-prefix{
            margin-right: 4px;
        }
        img{
            width:18px;
            height:18px;
        }
        text{
            font-size: 12px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }
    // 新增：年月切换区域样式
    .date-picker-container {
        border-radius: 5px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding:4px 8px;
        background-color: @card-bg;
        border-bottom: 1px solid @border-color;

        .arrow-icon {
            cursor: pointer;
            transition: all 0.2s ease;

            &:active {
                transform: scale(0.9);
                color: #1890ff;
            }
        }

        .current-date {
            display: flex;
            align-items: center;
            gap: 6px;
            margin: 0 5px;
            cursor: pointer;

            .date-text {
                font-size: 18px;
                font-weight: 500;
                color: @text-primary;
            }

            &:active .down-icon {
                transform: rotate(180deg);
            }
        }
    }

    // 收支概览区域
    .overview-container {
        padding: 16px 0px;

        .balance-card {
            background: linear-gradient(135deg, #f5fafe 0%, #eaf6fa 100%);
            border-radius: 16px;
            padding: 10px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

            .card-title {
                font-size: 14px;
                color: @text-secondary;
                display: block;
            }

            .total-balance {
                font-size: 32px;
                font-weight: 600;
                color: @text-primary;
                display: block;
                margin-bottom: 10px;
            }

            .income-expense {
                display: flex;
                justify-content: space-around;
                align-items: center;

                .item {
                    text-align: center;

                    .label {
                        font-size: 14px;
                        color: @text-secondary;
                        display: block;
                        margin-bottom: 4px;
                    }

                    .amount {
                        font-size: 14px;
                        font-weight: 500;
                    }
                }

                .divider {
                    width: 1px;
                    height: 30px;
                    background-color: @border-color;
                }
            }
        }
    }

    // 当月明细标题
    .monthly-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding:0px 5px 10px 5px;

        .title-text {
            font-size: 18px;
            font-weight: 600;
            color: @text-primary;
        }
    }
    .add-record-btn {
        position: fixed;
        bottom:100px;
        right:30px;
        background-color: #1890ff;
        border-radius: 50%;
        width:50px;
        height:50px;
        color:white;
        &::after {
            border: none;
            border-radius: 20px;
        }
    }
    // 收支明细列表
    .records-container {
        padding: 0px;

        .empty-tip {
            text-align: center;
            padding: 60px 0;
            color: @text-secondary;

            .empty-icon {
                font-size: 48px;
                display: block;
                margin-bottom: 16px;
            }

            .empty-text {
                font-size: 16px;
                display: block;
                margin-bottom: 8px;
            }

            .empty-desc {
                font-size: 14px;
                opacity: 0.8;
            }
        }
        .record-list{
            background: white;
            max-height: 420px;
            overflow: auto;
            border-radius: 16px;
            padding: 10px 0px;
            .record-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                border-radius: 12px;
                padding: 5px 10px;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
                transition: background-color 0.2s ease;

                &:active {
                    background-color: #f5f5f5;
                }

                .record-left {
                    display: flex;
                    align-items: center;
                }

                .record-icon {
                    width: 40px;
                    height: 40px;
                    border-radius: 8px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin-right: 12px;

                    .icon-text {
                        font-size: 20px;
                        color: @income-color;
                    }
                }

                .record-info {
                    .record-name {
                        font-size: 16px;
                        color: @text-primary;
                        display: block;
                    }

                    .record-time {
                        font-size: 12px;
                        color: @text-secondary;
                        display: block;
                        margin-top: 2px;
                    }
                }

                .record-amount {
                    font-size: 16px;
                    font-weight: 500;
                }
            }
        }

    }
    // 新增：年月选择器弹窗样式
    .date-popup {
        z-index: 999;
        .popup-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 16px;
            border-bottom: 1px solid @border-color;

            .popup-title {
                font-size: 16px;
                font-weight: 500;
                color: @text-primary;
            }


        }

        .picker-view {
            width: 100%;
            height: 200px;
            padding: 16px 0;
        }

        .picker-column {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .picker-item {
            font-size: 18px;
            color: @text-primary;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        :deep(.uni-popup__wrapper) {
            background-color:white!important;
        }
    }
    // 颜色类
    .income-color {
        color: @income-color;
    }

    .expense-color {
        color: @expense-color;
    }


</style>
